package com.media.appmedia.lock;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.media.appmedia.R;
import com.media.appmedia.base.BaseActivity;
import com.media.appmedia.base.BaseApplication;
import com.media.appmedia.entity.LockADBean;
import com.media.appmedia.network.ProtocolConst;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.slidingmenu.IntegralActivity;
import com.media.appmedia.util.FileUtils;
import com.media.appmedia.util.NetUtil;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.ToastUtils;
/**
 * 
 * 作者:	Rose
 * 业务名:
 * 功能说明: 锁屏主界面
 * 编写日期:	2014-12-3
 *
 */
public class LockScreenActivity extends BaseActivity implements
		OnPageChangeListener {
	// 屏蔽Home键使用
	// public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; // 需要自己定义标志
	private final String TAG = "LockScreenActivity";
	private SliderRelativeLayout sliderRelativeLayout;
	public static final int MSG_LOCK_SUCESS_RIGHT = 1;
	public static final int MSG_LOCK_SUCESS_LEFT = 2;
	private ViewPager mViewPager;
	private MainADViewPagerAdapter adapter;
	private ArrayList<ImageView> images;
	private ArrayList<String> goldLefts;
	private TextView leftText, RightText;
	private TextView times, timeData;
	private List<LockADBean> beans;

	private int typeRight;

	private HashMap<String, Boolean> rightCache = new HashMap<String, Boolean>();

	// 实时刷新时间
	private Handler timeHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				times.setText(getTime());
				timeData.setText(getDate());
			}
		};
	};

	//
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Home键屏蔽语句
		// this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED,
		// FLAG_HOMEKEY_DISPATCHED);// 关键代码
		setContentView(R.layout.activity_lock_screen);
		BaseApplication.getApplication().setLockActivity(this);
		sliderRelativeLayout = (SliderRelativeLayout) findViewById(R.id.sliderLayout);
		sliderRelativeLayout.setMainHandler(handler);
		sliderRelativeLayout.getBackground().setAlpha(180); // 设置背景的透明度

		leftText = (TextView) findViewById(R.id.left_text);
		RightText = (TextView) findViewById(R.id.right_text);
		// getRightLockGold();
		initViewPager();
		initData();
		mViewPager.setOnPageChangeListener(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		BaseApplication.getApplication().sendLock();
		if(BaseApplication.getApplication().returnIsOk && BaseApplication.getApplication().isOk()){
			initData();
		}

	}

	/**
	 * 
	 * 方法说明：数据生产
	 * 
	 */
	private void initData() {
		if (BaseApplication.getApplication().isOk()) {
			beans = BaseApplication.getApplication().getLockBeans();
			setViewPage();
		}
	}

	private void initViewPager() {
		times = (TextView) findViewById(R.id.text_time);
		timeData = (TextView) findViewById(R.id.text_days);
		Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/number.TTF");
		Typeface tf2 = Typeface.createFromAsset(getAssets(),
				"fonts/simheis.TTF");
		times.setTypeface(tf);
		timeData.setTypeface(tf2);
		times.setText(getTime());
		timeData.setText(getDate());
		// 启动线程刷新时间 1ms发送一次刷新，可更改
		new Thread() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
						timeHandler.sendEmptyMessage(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
		}.start();

		mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
		images = new ArrayList<ImageView>();
		adapter = new MainADViewPagerAdapter(images);
		mViewPager.setAdapter(adapter);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (beans == null || beans.size() == 0
					|| !NetUtil.isNetConn(getApplicationContext())) {
				finish();
				return;
			}
			if (MSG_LOCK_SUCESS_RIGHT == msg.what) {
				// virbate();
				putGold("you", beans.get(mViewPager.getCurrentItem())
						.getLock_image_id(), beans.get(typeRight)
						.getLock_image_photo());
				finish();
			} else if (MSG_LOCK_SUCESS_LEFT == msg.what) {
				// virbate();
				if (!NetUtil.isNetConn(getApplicationContext())) {
					finish();
					return;
				}
				Intent intent = new Intent(LockScreenActivity.this,
						LockADWebView.class);
				intent.putExtra("url",
						beans != null ? beans.get(mViewPager.getCurrentItem())
								.getLock_image_url() : "http//www.sgfc88.com");
				startActivity(intent);
				putGold("zuo",
						beans != null ? beans.get(mViewPager.getCurrentItem())
								.getLock_image_id() : "000000",
						beans.get(typeRight).getLock_image_photo());
				finish();
			}
		}
	};

	// /**
	// * 震动
	// */
	// private void virbate() {
	// Vibrator vibrator = (Vibrator) this
	// .getSystemService(Context.VIBRATOR_SERVICE);
	// vibrator.vibrate(200);
	// }

	/**
	 * 屏蔽掉返回键&Home键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	/**
	 * 
	 * 方法说明：获取当前日期，并格式化
	 * 
	 * @return
	 */

	private String getDate() {
		return (String) DateFormat.format("MM月dd日 EEEE", new Date());
	}

	/**
	 * 
	 * 方法说明：获取当前系统时间，并格式化
	 * 
	 * @return
	 */
	private String getTime() {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		CharSequence newTime = DateFormat.format("kk:mm", c);
		return newTime.toString();
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		if (arg0 < goldLefts.size()) {
			leftText.setText(goldLefts.get(arg0));
			typeRight = arg0;
			if (beans != null && beans.size() != 0) {
				getRight();
			}
		}
	}

	/**
	 * 
	 * 方法说明: 获取右滑解锁是否得金币 得多少？
	 * 
	 */
	private void getRightLockGold(String lock_image_id, String lock_image_photo) {
		ProtocolService.getLockRight(
				PhoneInfoUtils.getIMEI(getApplicationContext()), lock_image_id,
				lock_image_photo, new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> result) {
						try {
							boolean flage = false;
							JSONObject obj = new JSONObject(result.result);
							if (obj.getInt("message") == 1) {
								rightCache.put(
										obj.getString("lock_image_photo"), true);
								flage = true;
							} else {
								rightCache.put(
										obj.getString("lock_image_photo"),
										false);
							}
							if (beans.get(typeRight).getLock_image_photo()
									.equals(obj.getString("lock_image_photo"))) {
								if (flage) {
									RightText.setText("+2");
								} else {
									RightText.setText("");
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
					}
				});
	}

	/**
	 * 
	 * 方法说明：封装右边金币变化
	 * 
	 */
	private void getRight() {
		if (rightCache.containsKey(beans.get(typeRight).getLock_image_photo())) {
			if (rightCache.get(beans.get(typeRight).getLock_image_photo())) {
				RightText.setText("+2");
			} else {
				RightText.setText("");
			}
		} else {
			getRightLockGold(beans.get(typeRight).getLock_image_id(), beans
					.get(typeRight).getLock_image_photo());
		}
	}

	/**
	 * 
	 * 方法说明：获取解锁界面的广告数据源集合
	 * 
	 */
	private void setViewPage() {
		goldLefts = new ArrayList<String>();
		if (beans == null || beans.size() == 0) {
			leftText.setText("");
			if (NetUtil.isNetConn(getApplicationContext())) {
				String urlImg[] = new String[] { ProtocolConst.LOCK_IMAGE1,
						ProtocolConst.LOCK_IMAGE2, ProtocolConst.LOCK_IMAGE3,
						ProtocolConst.LOCK_IMAGE4 };
				BitmapUtils bitmapUtils = new BitmapUtils(
						getApplicationContext());
				for (int i = 0; i < 4; i++) {
					ImageView imageView = new ImageView(getApplicationContext());
					imageView.setLayoutParams(new LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.MATCH_PARENT));
					imageView.setScaleType(ScaleType.FIT_XY);
					bitmapUtils.display(imageView, urlImg[i]);
					images.add(imageView);
					goldLefts.add("");
				}
				adapter.notifyDataSetChanged();
			} else {
				/** 无网络时获取本地图片 */
				ImageView imageView = new ImageView(getApplicationContext());
				imageView.setLayoutParams(new LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
				imageView.setScaleType(ScaleType.FIT_XY);
				imageView.setImageResource(R.drawable.kaiji);
				images.add(imageView);
				goldLefts.add("");
				adapter.notifyDataSetChanged();
			}

		} else {
			for (int i = 0; i < beans.size(); i++) {
				BitmapUtils bitmapUtils = new BitmapUtils(
						getApplicationContext());
				ImageView imageView = new ImageView(getApplicationContext());
				imageView.setLayoutParams(new LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
				imageView.setScaleType(ScaleType.FIT_XY);
				bitmapUtils.display(imageView, FileUtils.createImgLoad()
						+ File.separator
						+ beans.get(i).getLock_image_photo().hashCode()
						+ ".png");
				images.add(imageView);
				goldLefts.add("+" + beans.get(i).getLock_image_leftjifen());
				adapter.notifyDataSetChanged();
			}
			Random random = new Random();
			int nonce;
			if (beans.size() == 1) {
				nonce = 0;
			} else {
				nonce = random.nextInt(beans.size() - 1);
			}
			mViewPager.setCurrentItem(nonce);
			typeRight = nonce;
			leftText.setText("+" + beans.get(nonce).getLock_image_leftjifen());
			getRight();
		}

	}

	/**
	 * 把Bitmap保存为文件
	 * 
	 * @param bitmap
	 *            图片源
	 * @param filePath
	 *            文件路径，要完整的
	 * @param format
	 *            保存的格式
	 * @throws Exception
	 */
	public void saveBitmap(Bitmap bitmap, String filePath, CompressFormat format)
			throws Exception {
		File file = new File(Environment.getExternalStorageDirectory(),
				filePath);
		String f = file.getAbsolutePath();
		OutputStream output = new FileOutputStream(f);
		bitmap.compress(format, 100, output);
		output.flush();
		output.close();
	}

	/**
	 * 
	 * 方法说明：上传解锁左右金币
	 * 
	 * @param direct
	 *            解锁方向
	 * @param id
	 *            获取的广告id
	 */
	private void putGold(String direct, String id, String lock_record_photo) {
		ProtocolService.putGold(
				PhoneInfoUtils.getIMEI(getApplicationContext()), id, direct,
				lock_record_photo, new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							// 增加金币的通知栏发送
							org.json.JSONObject obj = new org.json.JSONObject(
									arg0.result);
							if (obj.getInt("message") == 1) {
								if ("you".equals(obj.getString("type"))) {
									sendNotify("2");
								} else {
									if (obj.getInt("group") == 0) {
										FileUtils.deleteImage(beans.get(
												mViewPager.getCurrentItem())
												.getLock_image_photo());
										BaseApplication
												.getApplication()
												.delete(beans
														.get(mViewPager
																.getCurrentItem())
														.getLock_image_id());
									}
								}
							}
							
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
					}
				});
	}

	/**
	 * 
	 * 方法说明：发送通知栏消息，提示解锁得金币
	 * 
	 * @param gold
	 */
	private void sendNotify(String gold) {
		// 消息通知栏
		// 定义NotificationManager
		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				getApplicationContext());
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// 延迟意图对象
		Intent notificationIntent = new Intent(this, IntegralActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);

		// 设置通知栏内容
		builder.setContentTitle("赚乐淘友情提示：");
		builder.setContentText("您通过锁屏获取了" + gold + "金币");
		builder.setSmallIcon(R.drawable.ic_launcher);
		builder.setTicker("赚乐淘提示：您通过锁屏获取了" + gold + "金币");
		builder.setContentIntent(contentIntent);
		mNotificationManager.notify(1, builder.build());

	}

}
